<?php
/**
 * Created by PhpStorm.
 * User: g
 * Date: 2018/1/8
 * Time: 10:44
 */

namespace app\index\controller;


use app\index\validate\Valid;
use think\Request;
use think\Db;
use think\Session;
class Qdyhzcsq extends Commonwork
{
    public function index(){
        $eid=Session::get("employee_id");
        $sn = $this->request->get('sn');
        $this->assign('sn',$sn);
        $title = $this->request->get('title');
        $this->assign('title',$title);
        $status = $this->request->get('status');
        $this->assign('status',$status);
        $start = $this->request->get('start');
        $this->assign('start',$start);
        $end = $this->request->get('end');
        $this->assign('end',$end);

        $where = ["sqr"=>$eid];
        if($sn){
            $where['sn'] = ['like',"%{$sn}%"];
        }
        if($title){
            $where['title'] = ['like',"%{$title}%"];
        }
        if($status){
            $where['status'] = $status;
        }
        if($start&&$end){
            $where['sqtime'] = [['>',$start],['<',$end],'and'];
        }elseif($start&&!$end){
            $where['sqtime'] = ['>',$start];
        }elseif(!$start&&$end){
            $where['sqtime'] = ['<',$end];
        }

        $count = db('cg_channel_preferential_policy')->where($where)->count();
        $data = db('cg_channel_preferential_policy')->where($where)->order('sqtime desc,id desc')->paginate(10,$count);
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $v['sqr'] = db('employee')->where('id',$v['sqr'])->value('em_name');
            $v["myId"]=db("cg_workflow")->where(["yw_id"=>$v["id"],"ywlx"=>20])->value("id");
            $v["statustype"]=db("ti_state")->where(["id"=>$v["status"]])->value("title");
            $data[$k] = $v;
        }
        $this->assign([
            'page'=>$page,
            'data'=>$data,
        ]);
        return $this->fetch();
    }
    //审核
    public function shenhe($myId,$trackId,$workId)
    {
        $workfloawde=Db::table("cg_workflow")->where(["id"=>$myId])->find();
        $id=$workfloawde["yw_id"];

        $data = db('cg_channel_preferential_policy')->where('id',$id)->find();
        if($data["status"]==2){
            //打回
            $this->redirect('Qdyhzcsq/update', ['id' => $id,"from"=>1]);
        }else{
            $data['sqr'] = db('employee')->where('id',$data['sqr'])->value('em_name');
        $data['ssbm'] = db('department')->where('id',$data['ssbm'])->value('de_name');
        $this->assign('data',$data);

        //渠道政策明细
        $mingxi = db('cg_channel_preferential_policy_cxfa')->where('p_id',$id)->select();
        foreach($mingxi as $k=>$v){
            $v['area_id'] = unserialize($v['area_id']);
            foreach($v['area_id'] as $k2=>$v2){
                switch($v['area']){
                    case 1:
                        $v2 = db('cg_market_zoning')->where('id',$v2)->value('title');
                        break;
                    case 2:
                        $v2 = db('cg_market_provice')->where('id',$v2)->value('title');
                        break;
                    case 3:
                        $v2 = db('cg_market_city')->where('id',$v2)->value('title');
                        break;
                    defalut:
                        $v2 = db('cg_jxs')->where('id',$v2)->value('title');
                }
                $v['area_id'][$k2] = $v2;
            }
            $mingxi[$k] = $v;
        }
        $this->assign('mingxi',$mingxi);
         //查询方案
        $fa = db('cg_channel_preferential_policy_cxfa')->where('p_id',$id)->select();
        foreach($fa as $k=>$v){
            $v['area_id'] = unserialize($v['area_id']);
            $v['product_id'] = unserialize($v['product_id']);
            foreach($v['area_id'] as $k2=>$v2){
                $tmp_id = $v2;
                $v2 = [];
                $v2['id'] = $tmp_id;

                if($v['area']==2)
                    $v2['area_name'] = db('cg_market_provice')->where('id',$v2['id'])->value('title');
                elseif($v['area']==3)
                    $v2['area_name'] = db('cg_market_city')->where('id',$v2['id'])->value('title');
                elseif($v['area']==4)
                    $v2['area_name'] = db('cg_jxs')->where('id',$v2['id'])->value('title');
                else
                    $v2['area_name'] = db('cg_market_zoning')->where('id',$v2['id'])->value('title');$tmp_id = $v2;

                $v['area_id'][$k2] = $v2;
            }
            if($v['product_id']){
                foreach($v['product_id'] as $k2=>$v2){
                    $tmp_id = $v2;
                    $v2 = [];
                    $v2['id'] = $tmp_id;

                    if($v['product']==2)
                        $v2['area_name'] = db('pro_category')->where('id',$v2['id'])->value('category_name');
                    elseif($v['product']==3)
                        $v2['area_name'] = db('pro_series')->where('id',$v2['id'])->value('series_name');
                    elseif($v['product']==4)
                        $v2['area_name'] = db('pro_sku')->where('id',$v2['id'])->value('sku_name');
                    elseif($v['product']==5)
                        $v2['area_name'] = db('pro_products')->where('id',$v2['id'])->value('pro_name');
                    else
                        $v2['area_name'] = db('pro_brands')->where('id',$v2['id'])->value('brand_name');

                    $v['product_id'][$k2] = $v2;
                }
            }

            if($v['yhlx'])
            $v['yhlx'] = unserialize($v['yhlx']);
            if($v['chzk_reach'])
                $v['chzk_reach'] = unserialize($v['chzk_reach']);
            if($v['chzk_down'])
                $v['chzk_down'] = unserialize($v['chzk_down']);
            if($v['chzk_limit'])
                $v['chzk_limit'] = unserialize($v['chzk_limit']);
            if($v['agdjch_reach'])
                $v['agdjch_reach'] = unserialize($v['agdjch_reach']);
            if($v['agdjch_down'])
                $v['agdjch_down'] = unserialize($v['agdjch_down']);
            if($v['agdjch_limit'])
                $v['agdjch_limit'] = unserialize($v['agdjch_limit']);
            if($v['shdz_reach'])
                $v['shdz_reach'] = unserialize($v['shdz_reach']);
            if($v['shdz_gift'])
                $v['shdz_gift'] = unserialize($v['shdz_gift']);
            if($v['shdz_limit'])
                $v['shdz_limit'] = unserialize($v['shdz_limit']);
            if($v['shmj_reach'])
                $v['shmj_reach'] = unserialize($v['shmj_reach']);
            if($v['shmj_down'])
                $v['shmj_down'] = unserialize($v['shmj_down']);
            if($v['shmj_limit'])
                $v['shmj_limit'] = unserialize($v['shmj_limit']);
            if($v['chfd_reach'])
                $v['chfd_reach'] = unserialize($v['chfd_reach']);
            if($v['chfd_down'])
                $v['chfd_down'] = unserialize($v['chfd_down']);
            if($v['chfd_limit'])
                $v['chfd_limit'] = unserialize($v['chfd_limit']);
            $fa[$k] = $v;
        }
        $this->assign('fa',$fa);
         $logs=$this->getlog(20,$id);
         $this->assign("logs",$logs);
        return $this->fetch();
        }
        
    }
    //查看
    public function qpview(){
        $id = $this->request->param('id');

        $data = db('cg_channel_preferential_policy')->where('id',$id)->find();

        $data['sqr'] = db('employee')->where('id',$data['sqr'])->value('em_name');
        $data['ssbm'] = db('department')->where('id',$data['ssbm'])->value('de_name');
        $this->assign('data',$data);

        //渠道政策明细
        $mingxi = db('cg_channel_preferential_policy_cxfa')->where('p_id',$id)->select();
        foreach($mingxi as $k=>$v){
            $v['area_id'] = unserialize($v['area_id']);
            foreach($v['area_id'] as $k2=>$v2){
                switch($v['area']){
                    case 1:
                        $v2 = db('cg_market_zoning')->where('id',$v2)->value('title');
                        break;
                    case 2:
                        $v2 = db('cg_market_provice')->where('id',$v2)->value('title');
                        break;
                    case 3:
                        $v2 = db('cg_market_city')->where('id',$v2)->value('title');
                        break;
                    defalut:
                        $v2 = db('cg_jxs')->where('id',$v2)->value('title');
                }
                $v['area_id'][$k2] = $v2;
            }
            $mingxi[$k] = $v;
        }
        $this->assign('mingxi',$mingxi);
         //查询方案
        $fa = db('cg_channel_preferential_policy_cxfa')->where('p_id',$id)->select();
        foreach($fa as $k=>$v){
            $v['area_id'] = unserialize($v['area_id']);
            $v['product_id'] = unserialize($v['product_id']);
            foreach($v['area_id'] as $k2=>$v2){
                $tmp_id = $v2;
                $v2 = [];
                $v2['id'] = $tmp_id;

                if($v['area']==2)
                    $v2['area_name'] = db('cg_market_provice')->where('id',$v2['id'])->value('title');
                elseif($v['area']==3)
                    $v2['area_name'] = db('cg_market_city')->where('id',$v2['id'])->value('title');
                elseif($v['area']==4)
                    $v2['area_name'] = db('cg_jxs')->where('id',$v2['id'])->value('title');
                else
                    $v2['area_name'] = db('cg_market_zoning')->where('id',$v2['id'])->value('title');$tmp_id = $v2;

                $v['area_id'][$k2] = $v2;
            }
            if($v['product_id']){
                foreach($v['product_id'] as $k2=>$v2){
                    $tmp_id = $v2;
                    $v2 = [];
                    $v2['id'] = $tmp_id;

                    if($v['product']==2)
                        $v2['area_name'] = db('pro_category')->where('id',$v2['id'])->value('category_name');
                    elseif($v['product']==3)
                        $v2['area_name'] = db('pro_series')->where('id',$v2['id'])->value('series_name');
                    elseif($v['product']==4)
                        $v2['area_name'] = db('pro_sku')->where('id',$v2['id'])->value('sku_name');
                    elseif($v['product']==5)
                        $v2['area_name'] = db('pro_products')->where('id',$v2['id'])->value('pro_name');
                    else
                        $v2['area_name'] = db('pro_brands')->where('id',$v2['id'])->value('brand_name');

                    $v['product_id'][$k2] = $v2;
                }
            }

            if($v['yhlx'])
            $v['yhlx'] = unserialize($v['yhlx']);
            if($v['chzk_reach'])
                $v['chzk_reach'] = unserialize($v['chzk_reach']);
            if($v['chzk_down'])
                $v['chzk_down'] = unserialize($v['chzk_down']);
            if($v['chzk_limit'])
                $v['chzk_limit'] = unserialize($v['chzk_limit']);
            if($v['agdjch_reach'])
                $v['agdjch_reach'] = unserialize($v['agdjch_reach']);
            if($v['agdjch_down'])
                $v['agdjch_down'] = unserialize($v['agdjch_down']);
            if($v['agdjch_limit'])
                $v['agdjch_limit'] = unserialize($v['agdjch_limit']);
            if($v['shdz_reach'])
                $v['shdz_reach'] = unserialize($v['shdz_reach']);
            if($v['shdz_gift'])
                $v['shdz_gift'] = unserialize($v['shdz_gift']);
            if($v['shdz_limit'])
                $v['shdz_limit'] = unserialize($v['shdz_limit']);
            if($v['shmj_reach'])
                $v['shmj_reach'] = unserialize($v['shmj_reach']);
            if($v['shmj_down'])
                $v['shmj_down'] = unserialize($v['shmj_down']);
            if($v['shmj_limit'])
                $v['shmj_limit'] = unserialize($v['shmj_limit']);
            if($v['chfd_reach'])
                $v['chfd_reach'] = unserialize($v['chfd_reach']);
            if($v['chfd_down'])
                $v['chfd_down'] = unserialize($v['chfd_down']);
            if($v['chfd_limit'])
                $v['chfd_limit'] = unserialize($v['chfd_limit']);
            $fa[$k] = $v;
        }
        $this->assign('fa',$fa);
         $logs=$this->getlog(20,$id);
         $this->assign("logs",$logs);
        return $this->fetch();
    }
    public function add(){
        if($_POST){
            $data = Request::instance()->post();
            //dump($data);die;
            $valid = new Valid([
               'title|主题'=>'require',
               'sqr|申请人'=>'require',
               'ssbm|所属部门'=>'require',
               'sqtime|申请时间'=>'require',
               'start|优惠开始时间'=>'require',
               'end|优惠结束时间'=>'require',
               'area|区域'=>'require',
               'saleNum|无政策销量'=>'require',
               'policySaleNum|政策预计销量'=>'require',
               'estiGiftCost|预计搭赠产生的费用'=>'require',
            ]);
            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }
            if(!isset($data['area_id'])||count($data['area_id'])==0){
                switch($data['area']){
                    case 2:
                        $t = '省份';
                        break;
                    case 3:
                        $t = '城市';
                        break;
                    case 4:
                        $t = '经销商';
                        break;
                    default:
                        $t = '分区';
                }
                echo json_encode(['success'=>false,'msg'=>'请选择'.$t]);die;
            }
            $data['area_id'] = serialize($data['area_id']);
            if($data['savetype']=='save1'){
                $data['status']=1;
            }else{
                $data['status']=3;
            }
            unset($data['remove']);
            unset($data['savetype']);
            if($data['attach']){
                $attachids = $data['attach'];
                $data['attach'] = serialize(explode(',',$data['attach']));
            }
            //生成编号
            $sn = $this->produceSN();
            $data['sn'] = $sn;
            //增加计算费率
            if($data["policySaleNum"]){
                $data["estiCostRate"]=round($data["estiGiftCost"]/$data["policySaleNum"]*100,2);
            }else{
                $data["estiCostRate"]=0;
            }
            //增加计算回报率
            if($data["estiGiftCost"]){
                $data["estiReturnRate"]=round($data["saleInc"]/$data["estiGiftCost"]*100,2);
            }else{
                $data["estiReturnRate"]=0;
            }
            
            $ti_id = db('cg_channel_preferential_policy')->insertGetId($data);
            if(false!==$ti_id){
                //更新附件表
                if(isset($attachids)){
                    db('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$ti_id,'target_table'=>'cg_channel_preferential_policy'));
                }
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }
        $sqr = session('employee_id');
        $this->assign('sqr',$sqr);
        $em_name = db('employee')
            ->where(['id'=>$sqr])
            ->value('em_name');
        $this->assign('em_name',$em_name);
        $ssbm_id = db('department_employee')
            ->where(['index'=>1,'employee_id'=>$sqr])
            ->value('department_id');
        $this->assign('ssbm_id',$ssbm_id);
        $ssbm = db('department')
            ->where(['id'=>$ssbm_id])
            ->value('de_name');
        $this->assign('ssbm',$ssbm);

        //使用角色
        $syjs = db('role t')->join('users_role t2','t.id=t2.role_id')->where(['t2.users_id'=>session('login_id')])->field('t.id,t.role_name')->select();
        $this->assign('syjs',$syjs);

        return $this->fetch('form');
    }
    public function baocunchuli(){
        //echo 1;exit;
        $request = Request::instance();$datas = $request->post();
        $id=$datas["id"];
        $data['title'] = $this->request->post('title');
        $data['sqr'] = $this->request->post('sqr');
        $data['ssbm'] = $this->request->post('ssbm');
        $data['sqtime'] = $this->request->post('sqtime');
        $data['saleNum'] = $this->request->post('saleNum');
        $data['policySaleNum'] = $this->request->post('policySaleNum');
        $data['saleInc'] = $this->request->post('saleInc');
        $data['estiGiftCost'] = $this->request->post('estiGiftCost');
        $data['estiCostRate'] = $this->request->post('estiCostRate');
        $data['estiReturnRate'] = $this->request->post('estiReturnRate');
        $data['info'] = $this->request->post('info');
        $data['savetype'] = $this->request->post('savetype');
        $data['attach'] = $this->request->post('attach');
        $data['remove'] = $this->request->post('remove');
        $data['id'] = $id;
        $valid = new Valid([
               'title|主题'=>'require',
               'sqr|申请人'=>'require',
               'ssbm|所属部门'=>'require',
               'sqtime|申请时间'=>'require',
               'saleNum|无政策销量'=>'require',
               'policySaleNum|政策预计销量'=>'require',
               'estiGiftCost|预计搭赠产生的费用'=>'require',
            ]);
            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }
         unset($data['remove']);
            unset($data['savetype']);
            if($data['attach']){
                $attachids = $data['attach'];
                $data['attach'] = serialize(explode(',',$data['attach']));
            }

            $this->updateAttach($id);
             //增加计算费率
            if($data["policySaleNum"]){
                $data["estiCostRate"]=round($data["estiGiftCost"]/$data["policySaleNum"]*100,2);
            }else{
                $data["estiCostRate"]=0;
            }
            //增加计算回报率
            if($data["estiGiftCost"]){
                $data["estiReturnRate"]=round($data["saleInc"]/$data["estiGiftCost"]*100,2);
            }else{
                $data["estiReturnRate"]=0;
            }
            $data["status"]=3;
        $fid=20;$aid=$data["id"];
        $res=$this->goworker($fid,$aid,$datas["nodeKey"],$datas["selectId"],$datas["selectName"]);
        if($res["operateStatus"]=="success"){
            try{
                $ti_id = db('cg_channel_preferential_policy')->where('id',$id)->update($data);
            }catch (\Exception $e){
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            return json_encode(["msg"=>"","state"=>1]);
            
        }else{
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            
        }

        //print_r($data);exit;
    }
    public function update($from=1){
        $id = $this->request->param('id');
        $this->assign("from",$from);
        if($_POST){
            $data['title'] = $this->request->post('title');
            $data['sqr'] = $this->request->post('sqr');
            $data['ssbm'] = $this->request->post('ssbm');
            $data['sqtime'] = $this->request->post('sqtime');
            $data['saleNum'] = $this->request->post('saleNum');
            $data['policySaleNum'] = $this->request->post('policySaleNum');
            $data['saleInc'] = $this->request->post('saleInc');
            $data['estiGiftCost'] = $this->request->post('estiGiftCost');
            $data['estiCostRate'] = $this->request->post('estiCostRate');
            $data['estiReturnRate'] = $this->request->post('estiReturnRate');
            $data['info'] = $this->request->post('info');
            $data['savetype'] = $this->request->post('savetype');
            $data['attach'] = $this->request->post('attach');
            $data['remove'] = $this->request->post('remove');
            $data['id'] = $id;
            $valid = new Valid([
               'title|主题'=>'require',
               'sqr|申请人'=>'require',
               'ssbm|所属部门'=>'require',
               'sqtime|申请时间'=>'require',
               'saleNum|无政策销量'=>'require',
               'policySaleNum|政策预计销量'=>'require',
               'estiGiftCost|预计搭赠产生的费用'=>'require',
            ]);
            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }
            $data['status']=1;
            if($data['savetype']=='save1'){
                $status=1;
            }else{
                $status=3;
            }
            unset($data['remove']);
            unset($data['savetype']);
            if($data['attach']){
                $attachids = $data['attach'];
                $data['attach'] = serialize(explode(',',$data['attach']));
            }

            $this->updateAttach($id);
             //增加计算费率
            if($data["policySaleNum"]){
                $data["estiCostRate"]=round($data["estiGiftCost"]/$data["policySaleNum"]*100,2);
            }else{
                $data["estiCostRate"]=0;
            }
            //增加计算回报率
            if($data["estiGiftCost"]){
                $data["estiReturnRate"]=round($data["saleInc"]/$data["estiGiftCost"]*100,2);
            }else{
                $data["estiReturnRate"]=0;
            }
            $ti_id = db('cg_channel_preferential_policy')->where('id',$id)->update($data);
            if($status==3){
                $this->gowork(20,$id);
            }
            if(false!==$ti_id){
                echo json_encode(['success'=>true,'msg'=>'ok']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }
        $sqr = session('employee_id');
        $this->assign('sqr',$sqr);
        $em_name = db('employee')
            ->where(['id'=>$sqr])
            ->value('em_name');
        $this->assign('em_name',$em_name);
        $ssbm_id = db('department_employee')
            ->where(['index'=>1,'employee_id'=>$sqr])
            ->value('department_id');
        $this->assign('ssbm_id',$ssbm_id);
        $ssbm = db('department')
            ->where(['id'=>$ssbm_id])
            ->value('de_name');
        $this->assign('ssbm',$ssbm);
        $data = db('cg_channel_preferential_policy')->where('id',$id)->find();
        if($data["status"]==2){
                    $btn=$this->getbton(20,$id);
                    $this->assign("btn",$btn);
                    $logs=$this->getlog(20,$id);
                    //print_r($logs);
                    $this->assign("logs",$logs);
                }
        $this->assign('data',$data);
        //查询附件
        $attach = db('cg_channel_preferential_policy')->where('id',$id)->field('attach')->value('attach');
        if($attach){
            $attach = unserialize($attach);

            foreach($attach as $k=>$v){
                $temp = Db('annex')->where(array('id'=>$v))->find();

                $temp['path'] = '/uploads/'.$temp['path'];

                $attach[$k] = $temp;
            }
        }

        $this->assign('attach',$attach);

        //查询方案
        $fa = db('cg_channel_preferential_policy_cxfa')->where('p_id',$id)->select();
        foreach($fa as $k=>$v){
            $v['area_id'] = unserialize($v['area_id']);
            $v['product_id'] = unserialize($v['product_id']);
            foreach($v['area_id'] as $k2=>$v2){
                $tmp_id = $v2;
                $v2 = [];
                $v2['id'] = $tmp_id;

                if($v['area']==2)
                    $v2['area_name'] = db('cg_market_provice')->where('id',$v2['id'])->value('title');
                elseif($v['area']==3)
                    $v2['area_name'] = db('cg_market_city')->where('id',$v2['id'])->value('title');
                elseif($v['area']==4)
                    $v2['area_name'] = db('cg_jxs')->where('id',$v2['id'])->value('title');
                else
                    $v2['area_name'] = db('cg_market_zoning')->where('id',$v2['id'])->value('title');$tmp_id = $v2;

                $v['area_id'][$k2] = $v2;
            }
            if($v['product_id']){
                foreach($v['product_id'] as $k2=>$v2){
                    $tmp_id = $v2;
                    $v2 = [];
                    $v2['id'] = $tmp_id;

                    if($v['product']==2)
                        $v2['area_name'] = db('pro_category')->where('id',$v2['id'])->value('category_name');
                    elseif($v['product']==3)
                        $v2['area_name'] = db('pro_series')->where('id',$v2['id'])->value('series_name');
                    elseif($v['product']==4)
                        $v2['area_name'] = db('pro_sku')->where('id',$v2['id'])->value('sku_name');
                    elseif($v['product']==5)
                        $v2['area_name'] = db('pro_products')->where('id',$v2['id'])->value('pro_name');
                    else
                        $v2['area_name'] = db('pro_brands')->where('id',$v2['id'])->value('brand_name');

                    $v['product_id'][$k2] = $v2;
                }
            }

            if($v['yhlx'])
            $v['yhlx'] = unserialize($v['yhlx']);
            if($v['chzk_reach'])
                $v['chzk_reach'] = unserialize($v['chzk_reach']);
            if($v['chzk_down'])
                $v['chzk_down'] = unserialize($v['chzk_down']);
            if($v['chzk_limit'])
                $v['chzk_limit'] = unserialize($v['chzk_limit']);
            if($v['agdjch_reach'])
                $v['agdjch_reach'] = unserialize($v['agdjch_reach']);
            if($v['agdjch_down'])
                $v['agdjch_down'] = unserialize($v['agdjch_down']);
            if($v['agdjch_limit'])
                $v['agdjch_limit'] = unserialize($v['agdjch_limit']);
            if($v['shdz_reach'])
                $v['shdz_reach'] = unserialize($v['shdz_reach']);
            if($v['shdz_gift'])
                $v['shdz_gift'] = unserialize($v['shdz_gift']);
            //print_r($v['shdz_gift']);
            if($v['shdz_limit'])
                $v['shdz_limit'] = unserialize($v['shdz_limit']);
            if($v['shmj_reach'])
                $v['shmj_reach'] = unserialize($v['shmj_reach']);
            if($v['shmj_down'])
                $v['shmj_down'] = unserialize($v['shmj_down']);
            if($v['shmj_limit'])
                $v['shmj_limit'] = unserialize($v['shmj_limit']);
            if($v['chfd_reach'])
                $v['chfd_reach'] = unserialize($v['chfd_reach']);
            if($v['chfd_down'])
                $v['chfd_down'] = unserialize($v['chfd_down']);
            if($v['chfd_limit'])
                $v['chfd_limit'] = unserialize($v['chfd_limit']);
            $fa[$k] = $v;
        }
        $this->assign('fa',$fa);

        //使用角色
        $syjs = db('role t')->join('users_role t2','t.id=t2.role_id')->where(['t2.users_id'=>session('login_id')])->field('t.id,t.role_name')->select();
        $this->assign('syjs',$syjs);

        return $this->fetch('form');
    }

    /**
     * 删除
     */
    public function delete(){
        $id = $this->request->param('id');
        $attach = db('cg_channel_preferential_policy')->where('id',$id)->value('attach');
        $attach = unserialize($attach);
        db('annex')->where('id','in',$attach)->update(['isdel'=>1]);
        $bool = db('cg_channel_preferential_policy')->where('id',$id)->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'删除成功']);
        }else{
            echo json_encode(['success'=>false,'msg'=>'删除失败']);
        }
    }

    /**
     * 修改附件
     * @return mixed
     */
    private function updateAttach($id){
        $attach = $this->request->post('attach');
        $attach = trim($attach,',');
        $attachids = $attach;

        //先把旧的附件查出来
        $aids = db('cg_channel_preferential_policy')->where('id',$id)->value('attach');
        $old = $aids;
        if($aids){
            $aids = unserialize($aids);
        }
        if(!is_array($aids)){
            $aids = [];
        }

        //删除附件
        $remove = $this->request->post('remove');

        if($remove){

            $aids = array_diff($aids,explode(',',$remove));
            db('annex')->where('id','in',$remove)->update(['isdel'=>1]);
//                echo Db::table('annex')->getLastSql();
        }

        //新增附件
        if($attach) {
            $attachids = $attach;
            //新旧合并
            $attach = serialize(array_merge(explode(',', $attach), $aids));
        }else { //非新增
            $attach = serialize($aids);
        }

        $data = [];
        $data['attach'] = $attach;
        db('cg_channel_preferential_policy')->where(array('id'=>$id))->update($data);
        //新增附件\更新附件表
        if(isset($attachids)){

            db('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_channel_preferential_policy'));
        }

    }

    public function produceSN(){
        //生成编号
        $max = db('cg_channel_preferential_policy')->where('sn','like',date('Ymd').'%')->max('sn'); //编号递增开始位置基础

        if($max){
            $max = (double)$max;
            $insert_sn = $max+1;
        }else{
            $insert_sn = date('Ymd').'0001';
        }
        return $insert_sn;
    }

    //设置赠品
    public function szzp(){
        if($_POST){
            $data = $this->request->post('data/a');
            foreach($data as $k=>$v){
                $valid = new Valid([
                    'product|样品或物料'=>'require',
                    'num|数量'=>'require|number|>:0',
                ]);
                $bool = $valid->check($v);
                if(false==$bool){
                    echo  json_encode([
                        "success"=>false,
                        "msg"=>$valid->getError()
                    ]);die;
                }
            }
            die;
        }
        return $this->fetch();
    }
    //作废处理
    public function zuofeichuli(){
        $request = Request::instance();$data = $request->post();
       // print_r($data);exit;
        $fid=20;$aid=$data["id"];
        $res=$this->goworker($fid,$aid,$data["nodeKey"],$data["selectId"],$data["selectName"]);
        if($res["operateStatus"]=="success"){
            try{
                db("cg_channel_preferential_policy")->where(["id"=>$aid])->update(["status"=>8]);
            }catch (\Exception $e){
                return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
            }
            return json_encode(["msg"=>"","state"=>1]);
        }else{
            return json_encode(["msg"=>"系统繁忙请稍后再试","state"=>2]);
        }
    }
    //保存促销方案
    public function savecxfa(){
        if($_POST){
            $data = [];
            $data['title'] = $this->request->post('title');
            $data['sqr'] = $this->request->post('sqr');
            $data['ssbm'] = $this->request->post('ssbm');
            $data['sqtime'] = $this->request->post('sqtime');
            $data['saleNum'] = $this->request->post('saleNum');
            $data['policySaleNum'] = $this->request->post('policySaleNum');
            $data['saleInc'] = $this->request->post('saleInc');
            $data['estiGiftCost'] = $this->request->post('estiGiftCost');
            $data['info'] = $this->request->post('info');
            $valid = new Valid([
                'title|主题'=>'require',
                'sqr|申请人'=>'require',
                'ssbm|所属部门'=>'require',
                'sqtime|申请时间'=>'require',
            ]);
            if(!$valid->check($data)){
                echo json_encode(['success'=>false,'msg'=>$valid->getError()]);die;
            }

            $data2 = [];
            $data2['sfzd'] = $this->request->post('sfzd');
            $data2['start'] = $this->request->post('start');
            $data2['end'] = $this->request->post('end');
            $data2['area'] = $this->request->post('area');
            $data2['area_id'] = $this->request->post('area_id/a');
            $data2['product'] = $this->request->post('product');
            $data2['product_id'] = $this->request->post('product_id/a');
            $data2['yhlx'] = $this->request->post('yhlx/a');
            $data2['brief'] = $this->request->post('brief');
            if(in_array(3,$data2['yhlx'])){
                    $data2['chzk_unit'] = $this->request->post('chzk_unit');

                    $data2['chzk_reach'] = serialize($this->request->post('chzk_reach/a'));
                   // echo $data2['chzk_reach'];exit;
                    $data2['chzk_down'] = serialize($this->request->post('chzk_down/a'));
                    $data2['chzk_limit'] = serialize($this->request->post('chzk_limit/a'));
            }
            if(in_array(4,$data2['yhlx'])){
                    $data2['agdjch_unit'] = $this->request->post('agdjch_unit');
                    $data2['agdjch_reach'] = serialize($this->request->post('agdjch_reach/a'));
                    $data2['agdjch_down'] = serialize($this->request->post('agdjch_down/a'));
                    $data2['agdjch_limit'] = serialize($this->request->post('agdjch_limit/a'));
            }
            if(in_array(5,$data2['yhlx'])){
                     $data2['shdz_unit'] = $this->request->post('shdz_unit');
                    $data2['shdz_reach'] = serialize($this->request->post('shdz_reach/a'));
                    $data2['shdz_gift'] = serialize($this->request->post('shdz_gift/a'));
                    $data2['shdz_limit'] = serialize($this->request->post('shdz_limit/a'));
            }
            if(in_array(1,$data2['yhlx'])){
                    $data2['shmj_unit'] = $this->request->post('shmj_unit');
                    $data2['shmj_reach'] = serialize($this->request->post('shmj_reach/a'));
                    $data2['shmj_down'] = serialize($this->request->post('shmj_down/a'));
                    $data2['shmj_limit'] = serialize($this->request->post('shmj_limit/a'));
            }

            if(in_array(2,$data2['yhlx'])){
                    $data2['chfd_unit'] = $this->request->post('chfd_unit');
                    $data2['chfd_reach'] = serialize($this->request->post('chfd_reach/a'));
                    $data2['chfd_down'] = serialize($this->request->post('chfd_down/a'));
                    $data2['chfd_limit'] = serialize($this->request->post('chfd_limit/a'));
            }
                
            //print_r($data2);exit;
            if(!isset($data2['area_id'])||count($data2['area_id'])==0){
                switch($data2['area']){
                    case 2:
                        $t = '省份';
                        break;
                    case 3:
                        $t = '城市';
                        break;
                    case 4:
                        $t = '经销商';
                        break;
                    default:
                        $t = '分区';
                }
                echo json_encode(['success'=>false,'msg'=>'请选择'.$t]);die;
            }
            $data2['area_id'] = serialize($data2['area_id']);
            $data2['yhlx'] = serialize($data2['yhlx']);


            if($data2['sfzd']=='0'){
                if(!isset($data2['product_id'])||count($data2['product_id'])==0){
                    switch($data2['product']){
                        case 2:
                            $t = '品类';
                            break;
                        case 3:
                            $t = '系列';
                            break;
                        case 4:
                            $t = 'SKU';
                            break;
                        case 5:
                            $t = '单品';
                            break;
                        default:
                            $t = '品牌';
                    }
                    echo json_encode(['success'=>false,'msg'=>'请选择'.$t]);die;
                }
            }

            $data2['product_id'] = serialize($data2['product_id']);

            $data['status']=1;

            unset($data['remove']);
            if(isset($data['attach'])&&$data['attach']){
                $attachids = $data['attach'];
                $data['attach'] = serialize(explode(',',$data['attach']));
            }

            $id = $this->request->post('id');
            if(!$id){
                //生成编号
                $sn = $this->produceSN();
                $data['sn'] = $sn;
                 //增加计算费率
            if($data["policySaleNum"]){
                $data["estiCostRate"]=round($data["estiGiftCost"]/$data["policySaleNum"]*100,2);
            }else{
                $data["estiCostRate"]=0;
            }
            //增加计算回报率
            if($data["estiGiftCost"]){
                $data["estiReturnRate"]=round($data["saleInc"]/$data["estiGiftCost"]*100,2);
            }else{
                $data["estiReturnRate"]=0;
            }
                $id = db('cg_channel_preferential_policy')->insertGetId($data);
            }else{
                db('cg_channel_preferential_policy')->where('id',$id)->update($data);
            }
            if(false!==$id){
                //更新附件表
                if(isset($attachids)){
                    db('annex')->where(array('id'=>array('in',$attachids)))->update(array('target_id'=>$id,'target_table'=>'cg_channel_preferential_policy'));
                }
                $data2['p_id'] = $id;
                $fa_id = $this->request->post('fa_id');
                if($fa_id){
                    db('cg_channel_preferential_policy_cxfa')->where('id',$fa_id)->update($data2);
                }else{
                    $fa_id = db('cg_channel_preferential_policy_cxfa')->insertGetId($data2);
                }
                echo json_encode(['success'=>true,'msg'=>'ok','id'=>$id,'fa_id'=>$fa_id]);
            }else{
                echo json_encode(['success'=>false,'msg'=>'error']);
            }
            die;
        }
    }

    //删除促销方案
    public function deletecxfa(){
        $fa_id = $this->request->post('fa_id');
        $bool = db('cg_channel_preferential_policy_cxfa')->where('id',$fa_id)->delete();
        if(false!==$bool){
            echo json_encode(['success'=>true,'msg'=>'ok']);die;
        }else{
            echo json_encode(['success'=>false,'msg'=>'error']);die;
        }
    }

    //所属
    public function suoshu(){
        $sn = $this->request->param('sn');
        $title = $this->request->param('title');
        $is_revoke = $this->request->param('is_revoke');
        $start = $this->request->param('start');
        $end = $this->request->param('end');
        $this->assign([
            'sn'=>$sn,
            'title'=>$title,
            'is_revoke'=>$is_revoke,
            'start'=>$start,
            'end'=>$end,
        ]);
        $where = [];

        if($sn){
            $where['sn'] = ['like',"%{$sn}%"];
        }
        if($title){
            $where['title'] = ['like',"%{$title}%"];
        }
        if($is_revoke){
            $where['is_revoke'] = ['like',"%{$is_revoke}%"];
        }
        if($start){
            $where['sqtime'] = ['>=',$start];
        }
        if($end){
            $where['sqtime'] = ['<=',$end];
        }
        $where['sqr'] = session('employee_id');
        $count = db('cg_channel_preferential_policy')->where($where)->count();
        $data = db('cg_channel_preferential_policy')->where($where)->order('id desc')->paginate(10,$count);
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $v['sqr'] = db('employee')->where('id',$v['sqr'])->value('em_name');
            $v["myId"]=db("cg_workflow")->where(["yw_id"=>$v["id"],"ywlx"=>20])->value("id");
            $v["statustype"]=db("ti_state")->where(["id"=>$v["status"]])->value("title");
            $data[$k] = $v;
        }
        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch();
    }

    //撤销
    public function revoke(){
        $id = $this->request->param('id');
        if($_POST){
            $data = [];
            $data['revoke_time'] = $this->request->post('revoke_time');
            $data['revoke_reason'] = $this->request->post('revoke_reason');
            $data['is_revoke'] = 1;
            $bool = db('cg_channel_preferential_policy')->where('id',$id)->update($data);
            if(false !== $bool){
                echo json_encode(['success'=>true,'msg'=>'撤销成功']);
            }else{
                echo json_encode(['success'=>false,'msg'=>'撤销失败']);
            }
            die;
        }
        $data = db('cg_channel_preferential_policy')->where('id',$id)->find();

        $data['sqr'] = db('employee')->where('id',$data['sqr'])->value('em_name');
        $data['ssbm'] = db('department')->where('id',$data['ssbm'])->value('de_name');
        $this->assign('data',$data);

        //渠道政策明细
        $mingxi = db('cg_channel_preferential_policy_cxfa')->where('p_id',$id)->select();
        foreach($mingxi as $k=>$v){
            $v['area_id'] = unserialize($v['area_id']);
            foreach($v['area_id'] as $k2=>$v2){
                switch($v['area']){
                    case 1:
                        $v2 = db('cg_market_zoning')->where('id',$v2)->value('title');
                        break;
                    case 2:
                        $v2 = db('cg_market_provice')->where('id',$v2)->value('title');
                        break;
                    case 3:
                        $v2 = db('cg_market_city')->where('id',$v2)->value('title');
                        break;
                    defalut:
                        $v2 = db('cg_jxs')->where('id',$v2)->value('title');
                }
                $v['area_id'][$k2] = $v2;
            }
            $mingxi[$k] = $v;
        }
        $this->assign('mingxi',$mingxi);
        return $this->fetch();
    }

   

    //查询
    public function query(){
        $sn = $this->request->param('sn');
        $title = $this->request->param('title');
        $is_revoke = $this->request->param('is_revoke');
        $start = $this->request->param('start');
        $end = $this->request->param('end');
        $this->assign([
            'sn'=>$sn,
            'title'=>$title,
            'is_revoke'=>$is_revoke,
            'start'=>$start,
            'end'=>$end,
        ]);
        $where = [];

        if($sn){
            $where['sn'] = ['like',"%{$sn}%"];
        }
        if($title){
            $where['title'] = ['like',"%{$title}%"];
        }
        if($is_revoke){
            $where['is_revoke'] = ['like',"%{$is_revoke}%"];
        }
        if($start){
            $where['sqtime'] = ['>=',$start];
        }
        if($end){
            $where['sqtime'] = ['<=',$end];
        }
        $where['sqr'] = session('employee_id');
        $count = db('cg_channel_preferential_policy')->where($where)->count();
        $data = db('cg_channel_preferential_policy')->where($where)->order('id desc')->paginate(10,$count);
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $v['sqr'] = db('employee')->where('id',$v['sqr'])->value('em_name');
            $v["myId"]=db("cg_workflow")->where(["yw_id"=>$v["id"],"ywlx"=>20])->value("id");
            $v["statustype"]=db("ti_state")->where(["id"=>$v["status"]])->value("title");
            $data[$k] = $v;
        }
        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch();
    }
}